using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration;
using System.Text.Json;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 存储配置管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize(Policy = "AdminOnly")]
    public class StorageConfigurationController : ControllerBase
    {
        private readonly StorageConfigurationUnifier _configUnifier;
        private readonly IConfiguration _configuration;
        private readonly ILogger<StorageConfigurationController> _logger;
        private readonly IWebHostEnvironment _environment;

        public StorageConfigurationController(
            StorageConfigurationUnifier configUnifier,
            IConfiguration configuration,
            ILogger<StorageConfigurationController> logger,
            IWebHostEnvironment environment)
        {
            _configUnifier = configUnifier;
            _configuration = configuration;
            _logger = logger;
            _environment = environment;
        }

        /// <summary>
        /// 验证配置一致性
        /// </summary>
        /// <returns>验证结果</returns>
        [HttpGet("validate")]
        public ActionResult<ConfigValidationResult> ValidateConfiguration()
        {
            try
            {
                var result = _configUnifier.ValidateConfigurationConsistency();
                
                return Ok(new
                {
                    Success = !result.HasErrors(),
                    HasIssues = result.HasIssues(),
                    Errors = result.Errors,
                    Warnings = result.Warnings,
                    Summary = new
                    {
                        ErrorCount = result.Errors.Count,
                        WarningCount = result.Warnings.Count,
                        Status = result.HasErrors() ? "错误" : result.HasIssues() ? "警告" : "正常"
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "配置验证失败");
                return StatusCode(500, new { Error = "配置验证失败", Details = ex.Message });
            }
        }

        /// <summary>
        /// 获取统一的存储配置
        /// </summary>
        /// <returns>统一存储配置</returns>
        [HttpGet("unified")]
        public ActionResult<UnifiedStorageConfiguration> GetUnifiedConfiguration()
        {
            try
            {
                var config = _configUnifier.GetUnifiedStorageConfiguration();
                return Ok(config);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取统一配置失败");
                return StatusCode(500, new { Error = "获取统一配置失败", Details = ex.Message });
            }
        }

        /// <summary>
        /// 获取原始配置（Upload和CloudStorage）
        /// </summary>
        /// <returns>原始配置</returns>
        [HttpGet("raw")]
        public ActionResult GetRawConfiguration()
        {
            try
            {
                var uploadConfig = _configuration.GetSection("Upload");
                var cloudStorageConfig = _configuration.GetSection("CloudStorage");

                return Ok(new
                {
                    Upload = uploadConfig.Exists() ? uploadConfig.Get<Dictionary<string, object>>() : null,
                    CloudStorage = cloudStorageConfig.Exists() ? cloudStorageConfig.Get<Dictionary<string, object>>() : null,
                    Environment = _environment.EnvironmentName
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取原始配置失败");
                return StatusCode(500, new { Error = "获取原始配置失败", Details = ex.Message });
            }
        }

        /// <summary>
        /// 自动修复配置不一致问题
        /// </summary>
        /// <returns>修复结果</returns>
        [HttpPost("auto-fix")]
        public async Task<ActionResult> AutoFixConfiguration()
        {
            try
            {
                // 获取当前环境对应的配置文件路径
                var configFileName = _environment.EnvironmentName switch
                {
                    "Development" => "appsettings.Development.json",
                    "Production" => "appsettings.Production.json",
                    _ => "appsettings.json"
                };
                
                var configFilePath = Path.Combine(_environment.ContentRootPath, configFileName);
                
                if (!System.IO.File.Exists(configFilePath))
                {
                    return BadRequest(new { Error = "配置文件不存在", Path = configFilePath });
                }

                // 验证当前配置状态
                var validationResult = _configUnifier.ValidateConfigurationConsistency();
                
                if (!validationResult.HasIssues())
                {
                    return Ok(new 
                    { 
                        Message = "配置已经一致，无需修复",
                        ConfigFile = configFileName,
                        Status = "无需操作"
                    });
                }

                // 执行自动修复
                var success = await _configUnifier.AutoFixConfigurationAsync(configFilePath);
                
                if (success)
                {
                    return Ok(new
                    {
                        Message = "配置修复成功",
                        ConfigFile = configFileName,
                        FixedIssues = new
                        {
                            Errors = validationResult.Errors.Count,
                            Warnings = validationResult.Warnings.Count
                        },
                        Status = "修复成功"
                    });
                }
                else
                {
                    return StatusCode(500, new { Error = "配置修复失败", ConfigFile = configFileName });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "自动修复配置失败");
                return StatusCode(500, new { Error = "自动修复配置失败", Details = ex.Message });
            }
        }

        /// <summary>
        /// 修复所有环境的配置文件
        /// </summary>
        /// <returns>修复结果</returns>
        [HttpPost("fix-all-environments")]
        public async Task<ActionResult> FixAllEnvironments()
        {
            try
            {
                var configFiles = new[]
                {
                    "appsettings.json",
                    "appsettings.Development.json",
                    "appsettings.Production.json"
                };

                var results = new List<object>();

                foreach (var configFile in configFiles)
                {
                    var configPath = Path.Combine(_environment.ContentRootPath, configFile);
                    
                    if (System.IO.File.Exists(configPath))
                    {
                        var success = await _configUnifier.AutoFixConfigurationAsync(configPath);
                        results.Add(new
                        {
                            ConfigFile = configFile,
                            Path = configPath,
                            Success = success,
                            Status = success ? "修复成功" : "修复失败"
                        });
                    }
                    else
                    {
                        results.Add(new
                        {
                            ConfigFile = configFile,
                            Path = configPath,
                            Success = false,
                            Status = "文件不存在"
                        });
                    }
                }

                var successCount = results.Count(r => ((dynamic)r).Success);
                var totalCount = results.Count;

                return Ok(new
                {
                    Message = $"批量修复完成：{successCount}/{totalCount} 个文件修复成功",
                    Results = results,
                    Summary = new
                    {
                        Total = totalCount,
                        Success = successCount,
                        Failed = totalCount - successCount
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量修复配置失败");
                return StatusCode(500, new { Error = "批量修复配置失败", Details = ex.Message });
            }
        }

        /// <summary>
        /// 获取配置修复建议
        /// </summary>
        /// <returns>修复建议</returns>
        [HttpGet("recommendations")]
        public ActionResult GetConfigurationRecommendations()
        {
            try
            {
                var validationResult = _configUnifier.ValidateConfigurationConsistency();
                var recommendations = new List<object>();

                if (!validationResult.HasIssues())
                {
                    recommendations.Add(new
                    {
                        Type = "Info",
                        Message = "配置状态良好",
                        Description = "Upload 和 CloudStorage 配置保持一致",
                        Action = "无需操作"
                    });
                }
                else
                {
                    foreach (var error in validationResult.Errors)
                    {
                        recommendations.Add(new
                        {
                            Type = "Error",
                            Message = error.Message,
                            Description = error.Details ?? "需要立即修复",
                            Action = "执行自动修复或手动调整配置"
                        });
                    }

                    foreach (var warning in validationResult.Warnings)
                    {
                        recommendations.Add(new
                        {
                            Type = "Warning",
                            Message = warning.Message,
                            Description = warning.Details ?? "建议保持一致性",
                            Action = "建议统一配置以避免混乱"
                        });
                    }

                    // 添加通用建议
                    recommendations.Add(new
                    {
                        Type = "Suggestion",
                        Message = "统一存储配置管理",
                        Description = "建议使用 CloudStorage 配置作为主配置，Upload 配置保持兼容",
                        Action = "执行自动修复以统一配置"
                    });
                }

                return Ok(new
                {
                    ValidationStatus = validationResult.HasErrors() ? "错误" : validationResult.HasIssues() ? "警告" : "正常",
                    IssueCount = validationResult.Errors.Count + validationResult.Warnings.Count,
                    Recommendations = recommendations
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取配置建议失败");
                return StatusCode(500, new { Error = "获取配置建议失败", Details = ex.Message });
            }
        }
    }
}
